<script setup lang="ts">
import './app.scss';
import { ref, computed, onMounted, onUnmounted } from "vue";
// 直接使用全局Tauri对象，不预先赋值
import { getCurrentWindow, LogicalSize } from '@tauri-apps/api/window';
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';

// 扩展dayjs插件
dayjs.extend(duration);
import { ElMessage } from 'element-plus';
import { Solar, Lunar } from 'lunar-javascript';

// 日历相关状态
const currentCalendarDate = ref(dayjs());
// 默认时间设置为当前时间+1小时
const now = dayjs();
const selectedHour = ref(now.add(1, 'hour').hour());
const selectedMinute = ref(now.minute());
const selectedSecond = ref(now.second());
// 临时选择的日期（用于预览，未确认前不会更新目标日期）
const tempSelectedDate = ref(dayjs());

// 目标日期 - 从本地存储读取或设置为明天的当前时间
const getInitialTargetDate = () => {
  const savedDate = localStorage.getItem('countdown-target-date');
  if (savedDate) {
    const parsedDate = dayjs(savedDate);
    // 检查保存的时间是否已过期
    if (parsedDate.isAfter(dayjs())) {
      return parsedDate.toDate();
    }
  }
  // 如果没有保存的时间或时间已过期，返回默认时间
  return dayjs().add(1, 'day').add(1, 'hour').toDate();
};

const targetDate = ref(getInitialTargetDate());
// 倒计时数据
const countdown = ref({
  days: 0,
  hours: 0,
  minutes: 0,
  seconds: 0
});

// 日期选择器显示状态
const showDatePicker = ref(false);

// 隐藏其他元素状态（仅显示倒计时）
const hideOthers = ref(false);


// 定时器
let timer: number | null = null;



// 当前选择的完整日期时间（用于预览显示）
const selectedDateTime = computed(() => {
  return tempSelectedDate.value
    .hour(selectedHour.value)
    .minute(selectedMinute.value)
    .second(selectedSecond.value);
});

// 节假日列表 - 使用lunar-javascript库准确计算，只显示未来的节假日
const holidays = computed(() => {
  const currentYear = dayjs().year();
  const nextYear = currentYear + 1;
  const now = dayjs();
  const holidayList = [];
  
  // 生成当年和下一年的节假日
  for (const year of [currentYear, nextYear]) {
    // 元旦
    const newYear = dayjs(`${year}-01-01`);
    if (newYear.isAfter(now)) {
      holidayList.push({ name: '元旦', date: `${year}-01-01` });
    }
    
    // 春节（农历正月初一）
    const springFestival = Lunar.fromYmd(year, 1, 1).getSolar();
    const springDate = dayjs(springFestival.toYmd());
    if (springDate.isAfter(now)) {
      holidayList.push({ name: '春节', date: springFestival.toYmd() });
    }
    
    // 清明节（通过节气计算）
    let qingmingDate = null;
    for (let day = 4; day <= 6; day++) {
      const solar = Solar.fromYmd(year, 4, day);
      const jieQi = solar.getLunar().getJieQi();
      if (jieQi === '清明') {
        qingmingDate = solar.toYmd();
        break;
      }
    }
    const qingmingFinal = qingmingDate || `${year}-04-05`;
    const qingmingDay = dayjs(qingmingFinal);
    if (qingmingDay.isAfter(now)) {
      holidayList.push({ name: '清明节', date: qingmingFinal });
    }
    
    // 劳动节
    const laborDay = dayjs(`${year}-05-01`);
    if (laborDay.isAfter(now)) {
      holidayList.push({ name: '劳动节', date: `${year}-05-01` });
    }
    
    // 端午节（农历五月初五）
    const dragonBoat = Lunar.fromYmd(year, 5, 5).getSolar();
    const dragonBoatDate = dayjs(dragonBoat.toYmd());
    if (dragonBoatDate.isAfter(now)) {
      holidayList.push({ name: '端午节', date: dragonBoat.toYmd() });
    }
    
    // 中秋节（农历八月十五）
    const midAutumn = Lunar.fromYmd(year, 8, 15).getSolar();
    const midAutumnDate = dayjs(midAutumn.toYmd());
    if (midAutumnDate.isAfter(now)) {
      holidayList.push({ name: '中秋节', date: midAutumn.toYmd() });
    }
    
    // 国庆节
    const nationalDay = dayjs(`${year}-10-01`);
    if (nationalDay.isAfter(now)) {
      holidayList.push({ name: '国庆节', date: `${year}-10-01` });
    }
  }
  
  // 按日期排序，只返回最近的几个节假日
  return holidayList
    .sort((a, b) => dayjs(a.date).valueOf() - dayjs(b.date).valueOf())
    .slice(0, 8); // 最多显示8个即将到来的节假日
});

// 等待Tauri对象加载
const waitForTauri = () => {
  return new Promise<void>((resolve) => {
    const checkTauri = () => {
      if ((window as any).__TAURI__ && (window as any).__TAURI__.core && (window as any).__TAURI__.core.invoke) {
        resolve();
      } else {
        setTimeout(checkTauri, 100);
      }
    };
    checkTauri();
  });
};

// 计算倒计时
const calculateCountdown = async () => {
  try {
    await waitForTauri();
    
    const now = dayjs();
    const target = dayjs(targetDate.value);
    const diff = target.diff(now);
    
    if (diff <= 0) {
      countdown.value = { days: 0, hours: 0, minutes: 0, seconds: 0 };
      await updateTaskbarTitle();
      return;
    }
    
    const duration = dayjs.duration(diff);
    countdown.value = {
      days: Math.floor(duration.asDays()),
      hours: duration.hours(),
      minutes: duration.minutes(),
      seconds: duration.seconds()
    };
    
    await updateTaskbarTitle();
  } catch (error) {
    console.error('计算倒计时出错:', error);
  }
};

// 更新任务栏标题
const updateTaskbarTitle = async () => {
  try {
    await waitForTauri();
    const { days, hours, minutes, seconds } = countdown.value;
    
    // 如果倒计时已结束
    if (days === 0 && hours === 0 && minutes === 0 && seconds === 0) {
      await (window as any).__TAURI__.core.invoke('set_taskbar_title', { title: '倒计时已结束' });
      return;
    }
    
    // 根据剩余时间选择合适的显示格式
    let title = '';
    if (days > 0) {
      title = `${days}天${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    } else if (hours > 0) {
      title = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    } else {
      title = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    }
    
    await (window as any).__TAURI__.core.invoke('set_taskbar_title', { title });
  } catch (error) {
    console.error('更新标题出错:', error);
  }
};

// 选择节假日
const selectHoliday = (date: string) => {
  const holidayDateTime = dayjs(date);
  targetDate.value = holidayDateTime.toDate();
  
  // 保存目标时间到本地存储
  localStorage.setItem('countdown-target-date', holidayDateTime.toISOString());
  
  calculateCountdown();
};

/**
 * 打开日期选择器
 * 显示日期选择器并初始化状态
 */
const openDatePicker = () => {
  showDatePicker.value = true;
  // 初始化日历状态和临时选择状态
  const currentTarget = dayjs(targetDate.value);
  currentCalendarDate.value = currentTarget;
  tempSelectedDate.value = currentTarget;
  selectedHour.value = currentTarget.hour();
  selectedMinute.value = currentTarget.minute();
  selectedSecond.value = currentTarget.second();
};

/**
 * 关闭日期选择器
 */
const closeDatePicker = () => {
  showDatePicker.value = false;
};



/**
 * 更新选择的日期时间（通过输入框）
 * @param {Event} event - 输入事件
 */
const updateSelectedDateTime = (event: Event) => {
  const target = event.target as HTMLInputElement;
  const dateTimeValue = target.value;
  
  if (dateTimeValue) {
    const newDateTime = dayjs(dateTimeValue);
    tempSelectedDate.value = newDateTime;
    currentCalendarDate.value = newDateTime;
    selectedHour.value = newDateTime.hour();
    selectedMinute.value = newDateTime.minute();
    selectedSecond.value = newDateTime.second();
  }
};

/**
 * 确认日期选择
 */
const confirmDateSelection = () => {
  // 将临时选择的日期时间应用到目标日期
  const finalDateTime = tempSelectedDate.value
    .hour(selectedHour.value)
    .minute(selectedMinute.value)
    .second(selectedSecond.value);
  
  // 检查所选时间是否早于当前时间
  const now = dayjs();
  if (finalDateTime.isBefore(now)) {
    // 显示错误提示，不关闭弹窗
    ElMessage({
      message: '所选时间不能早于当前时间，请重新选择！',
      type: 'error',
      duration: 3000,
      showClose: true
    });
    return; // 不关闭弹窗，让用户重新选择
  }
  
  // 时间验证通过，应用目标日期
  targetDate.value = finalDateTime.toDate();
  
  // 保存目标时间到本地存储
  localStorage.setItem('countdown-target-date', finalDateTime.toISOString());
  
  // 显示成功提示
  ElMessage({
    message: '倒计时已开始！',
    type: 'success',
    duration: 2000
  });
  
  // 重新计算倒计时
  calculateCountdown();
  closeDatePicker();
};

/**
 * 快速设置日期
 * @param {string} type - 日期类型：today, tomorrow, week, month
 */
const setQuickDate = (type: string) => {
  const now = dayjs();
  let targetDateTime: dayjs.Dayjs;
  
  switch (type) {
    case 'today':
      targetDateTime = now.hour(23).minute(59).second(59);
      break;
    case 'tomorrow':
      targetDateTime = now.add(1, 'day').hour(9).minute(0).second(0);
      break;
    case 'week':
      targetDateTime = now.add(7, 'day').hour(9).minute(0).second(0);
      break;
    case 'month':
      targetDateTime = now.add(1, 'month').hour(9).minute(0).second(0);
      break;
    default:
      targetDateTime = now;
  }
  
  // 更新临时选择状态和日历显示
  tempSelectedDate.value = targetDateTime;
  currentCalendarDate.value = targetDateTime;
  selectedHour.value = targetDateTime.hour();
  selectedMinute.value = targetDateTime.minute();
  selectedSecond.value = targetDateTime.second();
  
  // 注意：不立即更新目标日期，需要用户点击确认按钮
};

// 格式化显示
const formattedCountdown = computed(() => {
  const { days, hours, minutes, seconds } = countdown.value;
  return {
    days: days.toString().padStart(2, '0'),
    hours: hours.toString().padStart(2, '0'),
    minutes: minutes.toString().padStart(2, '0'),
    seconds: seconds.toString().padStart(2, '0')
  };
});

// 最小化到任务栏
const minimizeToTaskbar = async () => {
  try {
    await waitForTauri();
    // 在隐藏窗口前确保任务栏标题已更新
    await updateTaskbarTitle();
    await (window as any).__TAURI__.core.invoke('hide_window');
  } catch (error) {
    console.error('隐藏窗口出错:', error);
    // 回退到使用getCurrentWindow API
    const window = getCurrentWindow();
    await window.hide();
  }
};

/**
 * 切换隐藏其他元素状态
 * 当启用时，仅显示倒计时并设置窗体高度为100px
 */
const toggleHideOthers = async () => {
  try {
    await waitForTauri();
    const window = getCurrentWindow();
    
    hideOthers.value = !hideOthers.value;
    
    if (hideOthers.value) {
      // 隐藏模式：设置窗体高度为100px，宽度保持不变
      await window.setSize(new LogicalSize(480, 80));
      // 禁用窗体大小调整
      await window.setResizable(false);
    } else {
      // 正常模式：恢复原始尺寸
      await window.setSize(new LogicalSize(480, 550));
      // 启用窗体大小调整
      await window.setResizable(true);
    }
  } catch (error) {
    console.error('切换窗体模式出错:', error);
    // 如果Tauri API调用失败，仍然切换状态（仅CSS效果）
    hideOthers.value = !hideOthers.value;
  }
};

// 组件挂载时启动倒计时
onMounted(() => {
  calculateCountdown();
  timer = window.setInterval(calculateCountdown, 1000);
});

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer !== null) {
    clearInterval(timer);
  }
});
</script>

<template>
  <div class="container">
    <div class="countdown-app" :class="{ 'hide-others-mode': hideOthers }">
      <h1 v-show="!hideOthers">倒计时</h1>
      
      <!-- 目标日期显示 - 可点击选择新日期 -->
      <div v-show="!hideOthers" class="target-date-info clickable" @click="openDatePicker">
        <span class="target-date-label"></span>
        <span class="target-date-value">{{ dayjs(targetDate).format('YYYY-MM-DD HH:mm:ss') }}</span>
        <span class="click-hint"></span>
      </div>
      
      <!-- 日期选择器弹窗 -->
      <div v-if="showDatePicker" class="date-picker-modal">
        <div class="modal-overlay" @click="closeDatePicker"></div>
        <div class="modal-content">
          <div class="modal-header">
            <h3 class="modal-title">选择目标日期</h3>
            <button class="modal-close" @click="closeDatePicker">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <line x1="18" y1="6" x2="6" y2="18"></line>
                <line x1="6" y1="6" x2="18" y2="18"></line>
              </svg>
            </button>
          </div>
          
          <div class="modal-body">
            <!-- 当前选择显示 -->
            <div class="selected-datetime-display">
              <label class="input-label">当前选择</label>
              <div class="selected-datetime-input">
                <input 
                  type="datetime-local" 
                  :value="selectedDateTime.format('YYYY-MM-DDTHH:mm:ss')" 
                  @input="updateSelectedDateTime"
                  class="datetime-input"
                />
              </div>
            </div>
            
            <div class="quick-select-section">
              <label class="input-label">快速选择</label>
              <div class="quick-date-buttons">
                <button class="quick-btn" @click="setQuickDate('today')">
                  <span class="quick-btn-icon">📅</span>
                  <span>今天</span>
                </button>
                <button class="quick-btn" @click="setQuickDate('tomorrow')">
                  <span class="quick-btn-icon">🌅</span>
                  <span>明天</span>
                </button>
                <button class="quick-btn" @click="setQuickDate('week')">
                  <span class="quick-btn-icon">📆</span>
                  <span>一周后</span>
                </button>
                <button class="quick-btn" @click="setQuickDate('month')">
                  <span class="quick-btn-icon">🗓️</span>
                  <span>一个月后</span>
                </button>
              </div>
            </div>
          </div>
          
          <div class="modal-footer">
            <el-button @click="closeDatePicker" class="cancel-btn">
              取消
            </el-button>
            <el-button type="primary" @click="confirmDateSelection" class="confirm-btn">
              确认并开始计时
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 倒计时显示 -->
      <div class="countdown-display">
        <span class="countdown-unit">
          <span class="countdown-number">{{ formattedCountdown.days }}</span>
          <span class="countdown-text">天</span>
        </span>
        <span class="countdown-unit">
          <span class="countdown-number">{{ formattedCountdown.hours }}</span>
          <span class="countdown-text">时</span>
        </span>
        <span class="countdown-unit">
          <span class="countdown-number">{{ formattedCountdown.minutes }}</span>
          <span class="countdown-text">分</span>
        </span>
        <span class="countdown-unit">
          <span class="countdown-number">{{ formattedCountdown.seconds }}</span>
          <span class="countdown-text">秒</span>
        </span>
      </div>
      
      <!-- 快速选择节假日按钮 -->
      <div v-show="!hideOthers" class="holiday-selector">
        <div class="holiday-buttons">
          <el-button 
            v-for="holiday in holidays" 
            :key="holiday.name"
            @click="selectHoliday(holiday.date)"
            size="small"
            class="holiday-btn"
          >
            {{ holiday.name }} ({{ holiday.date }})
          </el-button>
        </div>
      </div>
      
      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button v-show="!hideOthers" type="info" @click="minimizeToTaskbar">
          最小化到任务栏
        </el-button>
        <el-button 
          type="primary" 
          @click="toggleHideOthers"
          :class="{ 'show-all-btn': hideOthers }"
        >
          {{ hideOthers ? '☰' : '隐藏其他' }}
        </el-button>
      </div>
    </div>
  </div>
</template>

<!-- 样式已移至app.scss文件 -->